package com.duan.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by duanlsh on 18/9/16.
 */
public abstract class JwtUtil {

    private static String MY_SECRET = "e10adc3949ba59abbe56e057f20f883e";// 自己的加盐部分

    public static String createToken(String payload) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create().withHeader(map)
                .withClaim("payload", payload)
                .sign(Algorithm.HMAC256(MY_SECRET));// 加密
        return token;
    }


    public static Map<String, Claim>  verifyToken(String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(MY_SECRET)).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
//        System.out.println(claims.get("name").asString());
//        System.out.println(claims.get("age").asString());
        return claims;
    }

    public static void main(String[] args) throws Exception {
        String str = createToken("aa");
        System.out.println(str);
        verifyToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ91.eyJwYXlsb2FkIjoiYWEifQ.Jmp3OUNaPObbYOzmjrcPAjAjwIkU3U6T9aAmmGdCMhY");


    }

}
